package com.bjsxt.config.shiro;

import com.alibaba.fastjson.JSON;
import com.bjsxt.constants.HttpStatus;
import com.bjsxt.vo.AjaxResult;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class ShiroLoginFilter extends FormAuthenticationFilter {

    /**
     * shiro过滤器，在访问controller前判断是否登录，返回json，不进行重定向
     *
     * @param request
     * @param response
     * @return return=true继续往下运行，return=false未通过过滤器，不执行其他过滤器
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        servletResponse.setCharacterEncoding("UTF-8");
        servletResponse.setContentType("application/json");
        AjaxResult ajaxResult = AjaxResult.fail();
        ajaxResult.put("code", HttpStatus.UNAUTHORIZED);
        ajaxResult.put("msg", "登录失败，请重新登录");
        servletResponse.getWriter().write(JSON.toJSON(ajaxResult).toString());
        return false;
    }
}
